/**
 * Created by Bird on 2016/11/19.
 */
var http = require('http');
var formidable = require('formidable');

var server = http.createServer(function (req, res) {
    switch (req.method) {
        case 'GET':
            show(req, res);
            break;
        case 'POST':
            upload(req, res);
            break;
    }
});

server.listen(3000);

function show(req, res) {
    var html = '<form action="/" method="post" enctype="multipart/form-data">' +
        '<p><input type="text" name="name"/></p>' +
        '<p><input type="file" name="file"/></p>' +
        '<p><input type="submit" name="Upload"/></p>' +
        '</form>';
    res.setHeader('Content-Type', 'text/html');
    res.setHeader('Content-Length', Buffer.byteLength(html));
    res.end(html);
}

function upload(req, res) {
    if (!isFormData(req)) {
        res.statusCode = 400;
        res.end('Bad Request: expecting multipart/form-data');
        return;
    }
    var form = new formidable.IncomingForm();
    form.parse(req);

    form.on('field', function (field, value) {
        console.log('field event - field: ' + field);
        console.log('field event - value: ' + value);
    });

    form.on('file', function (name, file) {
        console.log('file event - name: ' + name);
        console.log('file event - file: ' + file);
    });

    form.on('progress', function (bytesReceived, bytesExpected) {
        var percent = Math.floor(bytesReceived / bytesExpected * 100);
        console.log('process: ' + percent);
    });

    form.on('end', function () {
        res.end('upload file ending');
    });


}

function isFormData(req) {
    var type = req.headers['content-type'] || '';
    return 0 == type.indexOf('multipart/form-data');
}